import router from '@/router';
import { useRoute } from 'vue-router';
import { useVxeGridUtils } from '@/composables/useVxeGridUtils';
import { useTagsViewStore } from '@/store';

export const useEvents = (options = {}) => {
  const {
    gridRef,
    API,
    actions,
    showSearch,
    showTree,
    selectedRows,
    selectedCount,
  } = options;
  const route = useRoute(); // 当前路由
  const {
    previousHandle,
    getDragParams,
    radioChangeHandle,
    checkBoxChangeHandle,
  } = useVxeGridUtils();
  const tagsViewStore = useTagsViewStore();

  const events = {
    // 工具栏左侧按钮点击
    toolbarButtonClick({ code }) {
      // 返回
      if (code === 'return_code') {
        return previousHandle(tagsViewStore, route, router);
      }

      // 按照code的命名，自动生成 方法名  dec_salary_code => decSalaryHandle
      const handlerName =
        code
          .replace(/_code$/, '') // 移除 "_code" 后缀
          .replace(/_(.)/g, (_, c) => c.toUpperCase()) + 'Handle'; // 转换为驼峰命名

      // 验证方法是否存在
      if (typeof actions[handlerName] !== 'function') {
        return console.error(`未定义的操作: ${handlerName}`);
      }
      const params = { rows: selectedRows.value };
      actions[handlerName](params);
    },
    // 工具栏右侧点击事件
    toolbarToolClick({ code }) {
      switch (code) {
        case 'search_code':
          showSearch.value = !showSearch.value;
          break;
        case 'tree_code':
          showTree.value = !showTree.value;
          break;
        case 'submit_code':
          gridRef?.value?.commitProxy('query');
          break;
        case 'reset_code':
          gridRef?.value?.commitProxy('initial');
          break;
      }
    },
    // 行拖拽事件
    async rowDragend(event) {
      const params = getDragParams(event, gridRef.value, 'sort');
      try {
        await API.drag(params);
        gridRef.value?.commitProxy('query');
      } catch (error) {
        console.error('Drag sort failed:', error);
      }
    },
    // 行编辑事件
    async editClosed({ row, column }) {
      try {
        await API.modify({
          id: row.id,
          field: column.field,
          value: row[column.field],
        });
        // 假设有消息提示
        // ElMessage.success('操作成功');
      } catch (error) {
        console.error('Edit closed failed:', error);
      }
    },
    // 单选事件
    radioChange({ row }) {
      selectedRows.value = [row];
      selectedCount.value = 1;
      radioChangeHandle(row, route);
    },
    // 多选事件
    checkboxChange({ records }) {
      selectedRows.value = records;
      selectedCount.value = records.length;
      checkBoxChangeHandle(records, route);
    },
    // 全选事件
    checkboxAll({ records }) {
      selectedRows.value = records;
      selectedCount.value = records.length;
      checkBoxChangeHandle(records, route);
    },
  };

  return { events, selectedRows, selectedCount };
};
